<?php


class area_helper
{
    /**
     * 根据地区id获取地区名称
     * 废弃方法
     */
    public static function get_area($area_id) {
        if (!$area_id) {
            return false;
        }

        $area_info = _uri('region', $area_id);

        $filter = array();
        $fitler['status'] = 1;
        $fitler['`lft` >= '] = $area_info['lft'];
        $filter['`rgt` <= '] = $area_info['rgt'];

        $area_list = _model('region')->getList($filter, 'ORDER BY `depth`');

        return $area_list;
    }

    /**
     * 通过行政地区代码获取地区信息
     */
    public static function get_area_info($area_code) {
        if (!$area_code) {
            return array();
        }

        return _uri('region', array('area_code' => $area_code));
    }

    /**
     * 解析地区编码, 获得完整的省市县数据
     * @param string $area_code
     * @return array
     */
    public static function parse_area_code($area_code = '000000') {
        return array(
            self::get_area_info(substr($area_code, 0, 2) == '00' ? '000000' : substr($area_code, 0, 2) . '0000'),
            self::get_area_info(substr($area_code, 2, 2) == '00' ? '000000' : substr($area_code, 0, 4) . '00'),
            self::get_area_info(substr($area_code, 4, 2) == '00' ? '000000' : $area_code),
        );
    }

    // 获取所有地区的数据
    // 格式['地区编码' => '地区名']
    public static function get_code_area_list() {
        $region_list = _model('region')->getList(array('1' => 1));
        $region_info = array();
        foreach ($region_list as $v) {
            if ($v['area_code'] > 0) {
                $region_info[$v['area_code']] = $v['area'];
            }
        }
        return $region_info;
    }


    /**
     * 根据地区名称获取地区编码
     * @param unknown $area 地区名称
     * @param unknown $depth 1=>省 2=>市 3=>1区
     */
    public static function get_area_code_by_area($area, $depth) {
        $filter = array();
        $filter['`area` LIKE '] = '%' . $area . '%';
        $filter['depth'] = $depth;

        $area_info = _uri('region', $filter);
        if ($area_info) {
            return $area_info['area_code'];
        } else {
            return 0;
        }
    }

    /**
     * 获取省编码索引的省份列表
     *
     * @return array
     * @throws AnException
     */
    public static function province_index() {
        $filter = array();
        $filter['depth'] = 1;
        $area = _model('region')->getList($filter);

        $province = array_to_filelds_assoc('area_code', $area);

        return $province;
    }
}

?>